package com.fzj.example.socket.tcp.nonblock;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ClassName: NioServer
 * date: 2019/11/18 10:57
 * Description: TODO
 *
 * @author fanzj@bonree.com
 * @since JDK 1.8
 */
public class NioServer {

    public static Map<String,SocketChannel> clientMap=new ConcurrentHashMap<String,SocketChannel>();

    public void init(int port){
        try {
            SocketChannel socketChannel=SocketChannel.open();
            socketChannel.bind(new InetSocketAddress(port));

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        try{
            ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
            serverSocketChannel.configureBlocking(false);
            serverSocketChannel.socket().bind(new InetSocketAddress(9932));
            Selector selector=Selector.open();
            //反向注册selector.register(ServerSocketChannelImpl,SelectionKey.OP_ACCEPT,null)
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            while (true){
                selector.select();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
